package services

import (
	"fmt"
	"net/url"

	"cashew.com/cashew_common/configs"
	"cashew.com/cashew_common/constants"
	"github.com/beego/beego/v2/core/logs"
)

func fillUserDetail(userDetail *UserDetail, userInfo *UserCache) {
	if userInfo != nil {
		userDetail.UserId = fmt.Sprintf("%d", userInfo.UserId)
		userDetail.Nick = userInfo.Nick
		if userInfo.HeadImg != "" && userInfo.HeadImg != "null" {
			userDetail.HeadImg = userInfo.HeadImg
		}
		userDetail.Age = userInfo.Age
		if userInfo.FlagImage != "" && userInfo.FlagImage != "null" {
			userDetail.FlagImage = CompleteURL(userInfo.FlagImage)
		}
		userDetail.Gender = userInfo.Gender
	}
}

type UserDetail struct {
	UserId    string `json:"user_id"`
	Nick      string `json:"nick"`
	HeadImg   string `json:"head_img"`
	Age       int    `json:"age"`
	FlagImage string `json:"flag_image"`
	Gender    int    `json:"gender"`
}

type ImVideocallCallRequest struct {
	NoticeUserId   string
	CallType       int
	PayPrice       int64
	AnchorPrice    int64
	AnchorId       int64
	CallerId       int64
	FromUserDetail UserDetail
	ToUserDetail   UserDetail
}

func ImVideocallCall(req *ImVideocallCallRequest) (err error) {
	postUrl := configs.WsHttpUrl
	headers := map[string]string{
		"Content-Type": "application/json",
	}
	queryParams := url.Values{}
	queryParams.Set("userid", req.NoticeUserId)
	queryParams.Set("service_code", "cashew_match")
	queryParams.Set("author_code", fmt.Sprintf("%d", constants.CHAT_CODE_VIDEOCALL))

	// 构建完整的请求URL，将查询参数添加到URL中
	reqUrl := postUrl + "?" + queryParams.Encode()
	reqBody := map[string]interface{}{
		"code": constants.CHAT_CODE_VIDEOCALL,
		"data": map[string]interface{}{
			"sub_code": constants.CHAT_CODE_VIDEOCALL_CALL,
			"data": map[string]interface{}{
				"from_user_id":     req.FromUserDetail.UserId,
				"to_user_id":       req.ToUserDetail.UserId,
				"call_type":        req.CallType,
				"pay_price":        fmt.Sprintf("%d", req.PayPrice),
				"anchor_price":     fmt.Sprintf("%d", req.AnchorPrice),
				"anchor_id":        fmt.Sprintf("%d", req.AnchorId),
				"from_user_detail": req.FromUserDetail,
				"to_user_detail":   req.ToUserDetail,
				//"caller_id":        fmt.Sprintf("%d", req.CallerId),
			},
		},
	}
	// 暂无
	respBody, err := HttpCall("POST", reqUrl, headers, reqBody)
	if err != nil {
		return
	}
	logs.Debug("响应体数据:%s", string(respBody))
	return
}

type ImVideocallAnswerRequest struct {
	NoticeUserId   string
	Guid           string
	StreamId       string
	HomeNum        string
	AnchorId       int64
	PayPrice       int64
	AnchorPrice    int64
	FromUserDetail UserDetail
	ToUserDetail   UserDetail
}

type ImConfirmCallRequest struct {
	NoticeUserId   string
	Guid           string
	StreamId       string
	HomeNum        string
	AnchorId       int64
	FromUserDetail UserDetail
	ToUserDetail   UserDetail
}

type UserWrongMsg struct {
	ErrorNo constants.ErrNo `json:"error_no"`
	Msg     string          `json:"msg"`
	Data    interface{}     `json:"data"`
}

// 通知用户报错信息
func ImUserWrongMsg(NoticeUserId string, errorNo constants.ErrNo, msg string, data interface{}) (err error) {
	postUrl := configs.WsHttpUrl
	headers := map[string]string{
		"Content-Type": "application/json",
	}
	queryParams := url.Values{}
	queryParams.Set("userid", NoticeUserId)
	queryParams.Set("service_code", "cashew_match")
	queryParams.Set("author_code", fmt.Sprintf("%d", constants.CHAT_CODE_VIDEOCALL))

	// 构建完整的请求URL，将查询参数添加到URL中
	url := postUrl + "?" + queryParams.Encode()
	dataMsg := UserWrongMsg{
		ErrorNo: errorNo,
		Msg:     msg,
		Data:    data,
	}

	dataSubCode := map[string]interface{}{
		"sub_code": constants.CHAT_CODE_WRONG_MSG,
		"data":     dataMsg,
	}
	reqBody := map[string]interface{}{
		"code": constants.CHAT_CODE_VIDEOCALL,
		"data": dataSubCode,
	}

	respBody, err := HttpCall("POST", url, headers, reqBody)
	if err != nil {
		return
	}
	logs.Debug("响应体数据:%s", string(respBody))
	logs.Info("IM 通知用户 userId:%s 终止任务信息成功：ImUserWrongMsg(%+v)", NoticeUserId, reqBody)
	return
}

// 在utils.RedisService结构体中添加获取指定用户所有离线消息的方法
// 定义一个结构体来匹配消息中的数据结构
type MessageData struct {
	FromUserID string `json:"from_user_id"`
	ToUserID   string `json:"to_user_id"`
	FromType   string `json:"from_type"`
	MsgType    string `json:"msg_type"`
	Msg        string `json:"msg"`
	Duration   int64  `json:"duration"`
	CreateTime int64  `json:"create_time"`
}

type ChatMessage struct {
	Code int         `json:"code"`
	Data MessageData `json:"data"`
}

func AssembleImVideocallQuickCallRequest(noticeUserId string, payPrice int64, anchorPrice int64, anchorId int64, viewerInfo *UserCache, anchorInfo *UserCache) ImVideocallCallRequest {
	req := ImVideocallCallRequest{
		NoticeUserId: noticeUserId, // 通知对方
		CallType:     constants.CALL_TYPE_RANDOM_MATCH,
		PayPrice:     payPrice,
		AnchorPrice:  anchorPrice,
		AnchorId:     anchorId,
	}

	fillUserDetail(&req.FromUserDetail, viewerInfo)
	fillUserDetail(&req.ToUserDetail, anchorInfo)

	return req
}
